<?php

namespace serv\queue\warehouse;

use of;
use L;
use of\base\com\mq;
use common\commonUpdateTrait;
use Sdk\Winit\CallApiUtil;
use common\batchInsert;
use traits\StockTrait;


class winit
{
    public static function pull($arr)
    {
        set_time_limit(0);
        try {
            $arr = $arr['data'];
            $method = 'queryWarehouseStorage';
            $page_size = 200;
            $current_page = 1;
            do {
                $data = [
                    'warehouseID' => $arr['warehouse_id'],
                    'warehouseCode' => $arr['warehouse_code'],
                    'pageSize' => $page_size,
                    'isActive' => 'Y',
                    'inReturnInventory' => 'N',
                    'pageNum' => $current_page
                ];
                $result = CallApiUtil::callWinitApi($method, $data);
                $rows = $result['data']['list'] ?? [];
                 if ($rows) {
                    $total_page = ceil($result['data']['total'] / $page_size);
                    foreach ($rows as $k => $val) {
                        $key = "check_winit_sku_stock_{$arr['warehouse_id']}_{$val['productCode']}";
                        $val = array_merge($val, ['warehouse_id' => $arr['warehouse_id']]);
                        //echo json_encode($val, JSON_UNESCAPED_UNICODE); exit;
                        mq::set(["checkWinitSkuStock", $key, $k], $val);
                    }
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);
            return true;
        } catch (Exception $exp) {
            return false;
        }
    }

    //检查或者更新
    public static function check($arr)
    {
        set_time_limit(0);
        try {
            of::work(['warehouse']);
            $val = $arr['data'];
            $sql = "SELECT stock_id, sku FROM stock WHERE 1 
                    AND warehouse_id = '{$val['warehouse_id']}' 
                    AND sku_code = '{$val['productCode']}';";
            $result = L::sql($sql, 'warehouse');
            if (!empty($result)) {
                //更新数据
                $data = [
                    'sku' => StockTrait::tran2sku($val['productCode']),
                    'available_stock' => $val['qtyAvailable'], //可用
                    'lock_stock' => $val['reservedInventory'], //锁
                    'stock' => $val['qtyAvailable'] + $val['reservedInventory'], //在库
                    'on_way_stock' => $val['pipelineInventory'],  //在途库存
                    'status' => StockTrait::stockStatus($val['productCode']),
                    'belong' => of::config('env.PUBLIC_BELONG'),
                    'updated_by' => of::config('env.SYSTEM_ID'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                //更新
                commonUpdateTrait::update('stock', $data, $result[0]['stock_id'], 'stock_id');
            } else {
                //插入数据
                $position = self::position($val['warehouse_id']);
                $data[] = [
                    'position_id' => !empty($position) ? $position['position_id'] : 1,
                    'area_id' => !empty($position) ? $position['area_id'] : 1,
                    'warehouse_id' => $val['warehouse_id'],
                    'sku' => StockTrait::tran2sku($val['productCode']),
                    'sku_code' => $val['productCode'],
                    'sku_name' => $val['productName'],
                    'sku_name_en' => $val['productName'],
                    'stock' => $val['qtyAvailable'] + $val['reservedInventory'],
                    'available_stock' => $val['qtyAvailable'],
                    'lock_stock' => $val['reservedInventory'],
                    'on_way_stock' =>  $val['pipelineInventory'], //在途
                    'status' => StockTrait::stockStatus($val['productCode']),
                    'belong' => of::config('env.PUBLIC_BELONG'),
                    'created_by' => of::config('env.SYSTEM_ID'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_by' => of::config('env.SYSTEM_ID'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                $sql = batchInsert::insert('stock', $data);
                L::sql($sql, 'warehouse');
            }
            of::work(true);
            return true;
        } catch (Exception $exp) {
            of::work($exp);
            return false;
        }
    }

    //获取此仓库默认库位
    private static function position($warehouse_id)
    {
        $sql = "SELECT position_id, area_id FROM `position` WHERE 1 AND warehouse_id = '{$warehouse_id}';";
        $rows = L::sql($sql, 'warehouse');
        return (!empty($rows)) ? $rows[0] : [];
    }


}